package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessions.AmiciziaManager;
import sessions.AmiciziaManagerRemote;
import sessions.UserManagerRemote;
import staticHtml.PaginaStatica;
import entities.Amicizia;
import entities.Utente;

public class VisualizzaAmiciServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		visualizza(request,response);

	}

	private void visualizza(HttpServletRequest request,
			HttpServletResponse response) throws IOException {



		Hashtable<String,String> env = new Hashtable<String,String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		env.put(Context.PROVIDER_URL,"localhost:1099");
		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		out.println(PaginaStatica.topUser());

		Utente utente= (Utente) request.getSession().getAttribute("utente");
		if(utente==null)
		{
			out.println("Sessione scaduta<br><a href='index.html'> Torna alla home </a>");
			out.println(PaginaStatica.bottom());
			return;
		}

		InitialContext jndiContext;
		try {
			jndiContext = new InitialContext(env);

			Object ref = jndiContext.lookup("AmiciziaManager/remote");
			AmiciziaManagerRemote amicizia = (AmiciziaManagerRemote) ref;

			List<Amicizia> amici=amicizia.getAmicizie(utente.getUserName());
			PaginaStatica.top();
			
			out.println("<div id='titolo'>	<label class='titolo'>Amici </label>	</div>");
			
			
			if(!amici.isEmpty()){
			out.println("<ul>");
			for(Amicizia a: amici)
			{
				out.println("<li>");
				if(a.getMittente().getUserName().compareTo(utente.getUserName())==0)
				{
			
					out.println("<form class ='risRicercaUtenti' style='margin-bottom: 25px;'>" +
							"<a href='paginaPersonale.html?name="+a.getDestinatario().getUserName()+"'>"+a.getDestinatario().getUserName()+"</a>");
					out.println("</form>");
				}
				else
				{
					out.println("<form class ='risRicercaUtenti' style='margin-bottom: 25px;'>" +
					"<a href='paginaPersonale.html?name="+a.getMittente().getUserName()+"'>"+a.getMittente().getUserName()+"</a>");
					out.println("</form>");
				}
				out.println("</li>");
				
			}
			out.println("<ul>");
			}
			else
			{
				out.println("Non hai amici =(<br>");
			}
			PaginaStatica.bottom();

		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}

}
